package com.imooc.listener;

import com.imooc.entity.User;
import com.imooc.util.SessionUtil;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;

@WebListener
public class MyHttpSessionListener implements HttpSessionListener{

    private int userNumber = 0;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        userNumber++;
        event.getSession().getServletContext().setAttribute("userNumber", userNumber);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        userNumber--;
        event.getSession().getServletContext().setAttribute("userNumber", userNumber);

        ArrayList<User> userList = null; //在线用户List

        userList = (ArrayList<User>) event.getSession().getServletContext().getAttribute("userList");

        if (SessionUtil.getUserBySessionId(userList, event.getSession().getId()) != null){
            userList.remove(SessionUtil.getUserBySessionId(userList, event.getSession().getId()));
        }
    }
}
